package com.ssm.sport.util;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ssm.sport.entity.User;
import com.ssm.sport.interceptor.UserAuthInterceptor;

/**
 * 用户上下文工具类
 * 用于在任何地方获取当前用户
 */
public class UserContext {
    
    private static final String USER_ID_PARAM = "userId";
    private static final String USER_ID_HEADER = "X-User-Id";
    
    /**
     * 获取当前请求
     * @return 当前请求
     */
    private static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }
    
    /**
     * 获取当前用户
     * @return 当前用户，如果未认证则返回null
     */
    public static User getCurrentUser() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        
        return UserAuthInterceptor.getCurrentUser(request);
    }
    
    /**
     * 获取当前用户ID
     * @return 当前用户ID，如果未认证则返回null
     */
    public static Integer getCurrentUserId() {
        User user = getCurrentUser();
        return user != null ? user.getId() : null;
    }
    
    /**
     * 获取请求中的用户ID
     * @return 请求中的用户ID，如果未提供则返回null
     */
    public static Integer getUserIdFromRequest() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        
        // 从请求参数获取
        String userId = request.getParameter(USER_ID_PARAM);
        if (userId != null && !userId.isEmpty()) {
            try {
                return Integer.parseInt(userId);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        
        // 从请求头获取
        userId = request.getHeader(USER_ID_HEADER);
        if (userId != null && !userId.isEmpty()) {
            try {
                return Integer.parseInt(userId);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        
        return null;
    }
} 